# -*- coding:utf-8 -*-
from PyQt5.QtCore import QSizeF
from PyQt5.QtGui import QTextDocument
from PyQt5.QtPrintSupport import QPrinterInfo,QPrinter

class Printer:
    # 获取可用打印机列表
    @staticmethod
    def getPrinterList():
        printer = []
        printerInfo = QPrinterInfo()
        for item in printerInfo.availablePrinters():
            printer.append(item.printerName)
        return printer


    # 打印任务 系统自动找可用打印机打印
    @staticmethod
    def doPrinting(context):
        p = QPrinter()
        doc = QTextDocument()
        doc.setHtml(context)
        doc.setPageSize(QSizeF(p.logicalDpiX() * 80/25.4),p.logicalDpiY() * (297 / 25.4))
        p.setOutputFormat(QPrinter.NativeFormat)
        doc.print_(p)

    #指定打印机名称打印
    @staticmethod
    def doSetPrinting(printer,context):
        printerInfo = QPrinterInfo()
        p = QPrinter()
        for item in printerInfo.availablePrinters():
            if printer == item.printerName:
                p = QPrinter(item)
                doc = QTextDocument()
                doc.setHtml(context)
                doc.setPageSize(QSizeF(p.logicalDpiX() * 80 / 25.4), p.logicalDpiY() * (297 / 25.4))
                p.setOutputFormat(QPrinter.NativeFormat)
                doc.print_(p)

test_html = """
    <table>
    <thead>
    <tr>
    <th>序号</th>
    <th>编号</th>
    <th>名称</th>
    <th>单位</th>
    <th>数量</th>
    <th>单价</th>
    <th>金额</th>
    <th>备注</th>
    </tr>
    </thead>
    <tr>
    <td>1</td>
    <td>001</td>
    <td>商品1</td>
    <td>件</td>
    <td>1</td>
    <td>1.00</td>
    <td>1.00</td>
    <td></td>
    </tr>
    <tr>
    <td>2</td>
    <td>002</td>
    <td>商品2</td>
    <td>件</td>
    <td>2</td>
    <td>2.00</td>
    <td>4.00</td>
    <td></td>
    </tr>
    <tr>
    <td>3</td>
    <td>003</td>
    <td>商品3</td>
    <td>件</td>
    <td>3</td>
    <td>3.00</td>
    <td>9.00</td>
    <td></td>
    </tr>
    <tbody>
    </tbody>
    </table>
"""

if __name__ == '__main__':
    print(Printer.getPrinterList())
    Printer.doPrinting(test_html)